<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 二分查找的代码
        // [left, right) 左闭右开
        var search = function(nums, target) {
            let left = 0;
            // 要写成right = nums.length，不是nums.length - 1，因为最后的right是没有意义的，可以取
            let right = nums.length;
            let mid;
            // 要写成left < right，因为[left, right)是没有意义的
            while (left < right) {
                mid = left + ((right - left) >> 1)
                if (nums[mid] > target) {
                    // 要写成right = mid，而不是mid+1
                    right = mid
                } else if (nums[mid] < target) {
                    left = mid + 1
                } else {
                    return mid
                }
            }
            return -1
        };
        console.log(search([-1, 0, 3, 5, 9, 12], 9));
        console.log(search([-1, 0, 3, 5, 9, 12], 12));
    </script>
</body>

</html>